<template>
  <div class="profile">
    <div class="profile-container">
      <!-- 个人信息卡片 -->
      <div class="profile-card">
        <div class="profile-header">
          <div class="avatar">
            <el-avatar :size="80" :src="userInfo.avatar">
              <el-icon size="40"><User /></el-icon>
            </el-avatar>
          </div>
          <div class="user-info">
            <h2>{{ userInfo.username }}</h2>
            <p class="role">
              <el-tag :type="userInfo.role === 'ADMIN' ? 'danger' : 'primary'">
                {{ getRoleText(userInfo.role) }}
              </el-tag>
            </p>
            <p class="join-time">加入时间：{{ formatDate(userInfo.createTime) }}</p>
          </div>
        </div>
        
        <div class="profile-stats">
          <div class="stat-item">
            <div class="stat-value">{{ borrowStats.totalBorrows || 0 }}</div>
            <div class="stat-label">总借阅数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ borrowStats.activeBorrows || 0 }}</div>
            <div class="stat-label">借阅中</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ borrowStats.overdueBorrows || 0 }}</div>
            <div class="stat-label">已逾期</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">¥{{ (borrowStats.totalFine || 0).toFixed(2) }}</div>
            <div class="stat-label">总罚金</div>
          </div>
        </div>
      </div>
      
      <!-- 个人信息编辑 -->
      <div class="info-card">
        <div class="card-header">
          <h3>个人信息</h3>
          <el-button type="primary" @click="handleEditInfo">
            <el-icon><Edit /></el-icon>
            编辑信息
          </el-button>
        </div>
        
        <div class="info-content">
          <div class="info-item">
            <label>用户名：</label>
            <span>{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <label>邮箱：</label>
            <span>{{ userInfo.email || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>手机号：</label>
            <span>{{ userInfo.phone || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>最后登录：</label>
            <span>{{ userInfo.lastLoginTime ? formatDate(userInfo.lastLoginTime) : '从未登录' }}</span>
          </div>
        </div>
      </div>
      
      <!-- 密码修改 -->
      <div class="password-card">
        <div class="card-header">
          <h3>密码安全</h3>
          <el-button type="warning" @click="handleChangePassword">
            <el-icon><Lock /></el-icon>
            修改密码
          </el-button>
        </div>
        
        <div class="password-content">
          <p>为了您的账户安全，建议定期更换密码。</p>
          <p>密码应包含字母、数字，长度不少于6位。</p>
        </div>
      </div>
    </div>
    
    <!-- 编辑信息对话框 -->
    <el-dialog
      v-model="infoDialogVisible"
      title="编辑个人信息"
      width="500px"
      @close="handleInfoDialogClose"
    >
      <el-form
        ref="infoFormRef"
        :model="infoForm"
        :rules="infoFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="infoForm.username"
            disabled
            placeholder="用户名不可修改"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="infoForm.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="infoForm.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="infoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateInfo" :loading="infoSubmitting">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      @close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordFormRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdatePassword" :loading="passwordSubmitting">
            修改密码
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { updateUserInfo, changePassword } from '@/api/user'
import { getMyBorrows } from '@/api/borrow'
import {
  User,
  Edit,
  Lock
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 计算属性
const userInfo = computed(() => userStore.userInfo)

// 加载状态
const infoSubmitting = ref(false)
const passwordSubmitting = ref(false)

// 借阅统计
const borrowStats = ref({})

// 对话框
const infoDialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const infoFormRef = ref()
const passwordFormRef = ref()

// 信息表单
const infoForm = reactive({
  username: '',
  email: '',
  phone: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 信息表单验证规则
const infoFormRules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 密码表单验证规则
const passwordFormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 获取角色文本
const getRoleText = (role) => {
  switch (role) {
    case 'ADMIN':
      return '管理员'
    case 'USER':
      return '普通用户'
    default:
      return '未知'
  }
}

// 加载借阅统计
const loadBorrowStats = async () => {
  try {
    const response = await getMyBorrows({ current: 1, size: 1 })
    borrowStats.value = response.data.stats || {}
  } catch (error) {
    console.error('加载借阅统计失败:', error)
  }
}

// 编辑信息
const handleEditInfo = () => {
  Object.assign(infoForm, {
    username: userInfo.value.username,
    email: userInfo.value.email || '',
    phone: userInfo.value.phone || ''
  })
  infoDialogVisible.value = true
}

// 修改密码
const handleChangePassword = () => {
  Object.assign(passwordForm, {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  passwordDialogVisible.value = true
}

// 更新个人信息
const handleUpdateInfo = async () => {
  try {
    await infoFormRef.value.validate()
    infoSubmitting.value = true
    
    const data = {
      email: infoForm.email,
      phone: infoForm.phone
    }
    
    await updateUserInfo(data)
    
    // 更新本地用户信息
    await userStore.fetchUserInfo()
    
    ElMessage.success('个人信息更新成功')
    infoDialogVisible.value = false
  } catch (error) {
    console.error('更新个人信息失败:', error)
  } finally {
    infoSubmitting.value = false
  }
}

// 修改密码
const handleUpdatePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordSubmitting.value = true
    
    const data = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    }
    
    await changePassword(data)
    
    ElMessage.success('密码修改成功，请重新登录')
    passwordDialogVisible.value = false
    
    // 退出登录
    setTimeout(() => {
      userStore.logout()
    }, 1000)
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    passwordSubmitting.value = false
  }
}

// 重置信息表单
const resetInfoForm = () => {
  Object.assign(infoForm, {
    username: '',
    email: '',
    phone: ''
  })
  infoFormRef.value?.clearValidate()
}

// 重置密码表单
const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  passwordFormRef.value?.clearValidate()
}

// 信息对话框关闭
const handleInfoDialogClose = () => {
  resetInfoForm()
}

// 密码对话框关闭
const handlePasswordDialogClose = () => {
  resetPasswordForm()
}

// 初始化
onMounted(() => {
  loadBorrowStats()
})
</script>

<style scoped>
.profile {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.profile-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profile-card {
  background: #fff;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
}

.avatar {
  flex-shrink: 0;
}

.user-info h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.role {
  margin: 0 0 8px 0;
}

.join-time {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.profile-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.info-card,
.password-card {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item label {
  width: 80px;
  color: #666;
  font-weight: 500;
}

.info-item span {
  color: #333;
}

.password-content {
  color: #666;
  line-height: 1.6;
}

.password-content p {
  margin: 0 0 8px 0;
}

.dialog-footer {
  text-align: right;
}

@media (max-width: 768px) {
  .profile {
    padding: 16px;
  }
  
  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .profile-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .info-item label {
    width: auto;
  }
}
</style>